package com.oocl.im.server;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.oocl.im.pojo.MsgPackage;
import com.oocl.im.pojo.Operation;

public class Server {
	private HashMap<String, Handler> handlerPool = new HashMap<>();
	ExecutorService es = Executors.newFixedThreadPool(8);

	void start() throws Exception {
		ServerSocket server = new ServerSocket(8123);
		while (true) {
			// init socket and it's stream.
			Socket socket = server.accept();
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

			// validate login info and dispatch handler thread.
			MsgPackage msg = (MsgPackage) in.readObject();
			String name = msg.getSender();
			int errorFlag = 0;
			if (msg.getOpeartion() != Operation.LOGIN)
				errorFlag = 1;
			else if (handlerPool.containsKey(name) && handlerPool.get(name) != null)
				errorFlag = 2;
			else if ("all".equals(name))
				errorFlag = 3;
			else if (name == null || !name.matches("[\\w\\u4E00-\\u9FA5_]+"))
				errorFlag = 4;
			switch (errorFlag) {
			case 0:
				System.out.println(name + " login");
				Handler handler = new Handler(name, socket, in, out, handlerPool);
				handlerPool.put(name, handler);
				es.submit(handler);
				break;
			case 1:
				MsgPackage msgPackage = new MsgPackage(Operation.EXIT, null, null, "you have not login", null, null);
				out.writeObject(msgPackage);
				socket.close();
				break;
			case 2:
				msgPackage = new MsgPackage(Operation.EXIT, null, null, "you have login", null, null);
				out.writeObject(msgPackage);
				socket.close();
				break;
			case 3:

			case 4:
				msgPackage = new MsgPackage(Operation.EXIT, null, null, "illegal name", null, null);
				out.writeObject(msgPackage);
				socket.close();
				break;
			default:
				break;
			}

		}
	}

	public static void main(String[] args) throws Exception {
		new Server().start();
	}

}
